package util

import (
	"github.com/spf13/cast"
	"math/rand/v2"
	"reflect"
	"runtime"
)

func NumCPU() int {
	return runtime.NumCPU()
}

// RandIntN 获得随机数
func RandIntN(i int) int {
	if i <= 1 {
		return 0
	}
	return rand.IntN(i)
}

// RandRange 按范围取随机值 [min, max)
func RandRange(min, max int) int {
	if max <= min {
		min, max = max, min
	}
	return RandIntN(max-min) + min
}

func InArray(needle any, haystack any) bool {
	val := reflect.ValueOf(haystack)
	switch val.Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < val.Len(); i++ {
			if reflect.DeepEqual(needle, val.Index(i).Interface()) {
				return true
			}
		}
	case reflect.Map:
		for _, k := range val.MapKeys() {
			if reflect.DeepEqual(needle, val.MapIndex(k).Interface()) {
				return true
			}
		}
	default:
		return false
	}
	return false
}

func AnyToInt64(v any) (ret int64) {
	return cast.ToInt64(v)
}

func AnyToFloat64(v any) (ret float64) {
	return cast.ToFloat64(v)
}

func AnyToStr(v any) (ret string) {
	return cast.ToString(v)
}

func AnyToBool(v any) bool {
	return cast.ToBool(v)
}
